package com.zhb.parse;

import com.zhb.beans.Course;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

/*
 * 设置对慕课网上课程数据的匹配规则，
 * 并返回获取到的数据
 */
public class CourseParse {
    public static List<Course> getData(String html) throws Exception {
        //获取的数据，存放在集合中
        List<Course> data = new ArrayList<Course>();
        //采用Jsoup解析
        Document doc = Jsoup.parse(html);
        //获取html标签中的内容
        Elements elements = doc.select("div[class=course-card-container]");
        for (Element ele : elements) {
//        	遍历获取页面中对象的值
            String course_id = ele.select("a[class=course-card]").attr("href");
            String course_name = ele.select("div[class=course-card-content]").select("h3").text();
            String course_img = ele.select("div[class=course-card-top]").select("img[class=course-banner lazy]").attr("data-original");
            String course_lable = ele.select("div[class=course-card-top]").select("div[class=course-label]").select("label").text();
            String course_level = ele.select("div[class=course-card-content]").select("div[class=clearfix course-card-bottom]").select("div[class=course-card-info]").select("span").text();
            String course_describe = ele.select("div[class=course-card-content]").select("div[class=clearfix course-card-bottom]").select("p[class=course-card-desc]").text();
            String learn_num = ele.select("div[class=course-card-content]").select("div[class=clearfix course-card-bottom]").select("div[class=course-card-info]").select("span").text();
            String course_cfa = "前沿技术";


            //创建一个对象，这里可以看出，使用Model的优势，直接进行封装
            Course course = new Course();
            //对象的值
            course.setCourseId(course_id.substring(course_id.lastIndexOf("/") + 1));
//            course.setCourseId(course_id);
            System.out.println("course_id:================" + course_id);
            course.setCourseName(course_name);
            course.setCourseImg(course_img.substring(course_img.lastIndexOf("/") + 1));
//            course.setCourseImg(course_img);
            System.out.println("course_img:================" + course_img);
            course.setCourseLable(course_lable);
            course.setCourseLevel(course_level.substring(0, 2));
            course.setCourseDescribe(course_describe);
            course.setLearnNum(learn_num.substring(2));
            course.setCourseCfa(course_cfa);
            //将每一个对象的值，保存到List集合中
            data.add(course);

        }
        System.out.println(data);
        //返回数据
        return data;
    }
}
